package me.hetong.caigou.ui.view;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import javafx.application.Platform;
import javafx.concurrent.Worker;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import me.hetong.caigou.entity.Zhao;
import me.hetong.caigou.ui.chessboard.ChessBoardWar;
import netscape.javascript.JSException;
import netscape.javascript.JSObject;

import java.awt.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;

import static me.hetong.caigou.Global.config;
import static me.hetong.caigou.Global.qipu;

public class LineChartWebView {

    private static JSObject javascriptObject;
    /**
     * 在这里new对象是为了防止app被回收，导致我们点击无效
     */
    private static LineChartWebViewHtmlToJavaConnector java = new LineChartWebViewHtmlToJavaConnector();

    public static WebView init() {

        WebView webView = new WebView();
        webView.setPrefHeight(150);
        webView.setPrefWidth(config.getRightWidth());
        webView.minWidth(config.getRightWidth());
        webView.setMaxWidth(config.getRightWidth());

        WebEngine engine = webView.getEngine();

        /*
         设备引擎背景透明
         */
        {
            try {
                Field f = engine.getClass().getDeclaredField("page");
                f.setAccessible(true);
                Object page = f.get(engine);
                Method m = page.getClass().getMethod("setBackgroundColor", int.class);
                m.setAccessible(true);
                m.invoke(page, (new Color(0, 0, 0, 0)).getRGB());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        engine.load(LineChartWebView.class.getResource("/html/score-chart.html").toExternalForm());
        Platform.runLater(() -> {
            try {
                engine.getLoadWorker().stateProperty().addListener((observable, oldValue, newValue) -> {
                    if (newValue == Worker.State.SUCCEEDED) {
                        javascriptObject = (JSObject) engine.executeScript("window");//获取浏览器引擎中的javascript语言中的window全局对象
                        javascriptObject.setMember("java", java);
                    }
                });
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
        return webView;
    }

    /**
     * 设置折线图参数
     */
    public static void transFromMatchData() {
        Platform.runLater(() -> {
            try {

                if (ChessBoardWar.isInfering) {
                    return;
                }

                javascriptObject.call("showResult", JSONUtil.toJsonStr(qipu.getZhaoList()));

//                JSONArray data1 = new JSONArray();
//                JSONArray data2 = new JSONArray();
//                JSONArray data3 = new JSONArray();
////                JSONArray data4 = new JSONArray();
//
//                int min = Integer.MAX_VALUE;
//                int max = Integer.MIN_VALUE;
//
//                List<Zhao> zhaoList = qipu.getZhaoList();
//
//                if (CollUtil.isNotEmpty(zhaoList)) {
//                    for (int i = 0; i < zhaoList.size(); i++) {
//                        Zhao zhao = zhaoList.get(i);
//                        data1.put(i + 1);
//                        data3.put(zhao.getName());
//                        Integer score = zhao.getScore();
//                        if (score != null) {
//                            min = score < min ? score : min;
//                            max = score > max ? score : max;
//                            data2.put(score);
//                        } else {
//                            data2.put(0);
//                        }
//
////                        if (zhao.getMate() != null) {
////                            String aa = "{xAxis:" + zhao.getMate() + "}";
////                            data4.add(aa);
////                        }
//                    }
//
//                    JSONObject entries = new JSONObject();
//                    entries.putOnce("data1", data1);
//                    entries.putOnce("data2", data2);
//                    entries.putOnce("data3", data3);
////                    entries.putOnce("data4", data4);
//                    entries.putOnce("min", min);
//                    entries.putOnce("max", max);
//                    entries.putOnce("title", qipu.getTitle());
//                    entries.putOnce("desc", qipu.getRedTeam() + qipu.getRed() + " " + qipu.getResult() + " " + qipu.getBlackTeam() + qipu.getBlack());
//
//                    String jsonStr = JSONUtil.toJsonStr(entries);
//                    Platform.runLater(() -> {
//                        javascriptObject.call("showResult", jsonStr);
//                    });
//                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    public static void setHighLight(int idx) {

        if (ChessBoardWar.isInfering) {
            return;
        }

        try {
            javascriptObject.call("setHighLight", idx);
        } catch (JSException e) {
            e.printStackTrace();
        }
    }
}